package fr.enseirb.webxml.servlet;

import java.util.Properties;
import java.util.HashMap;
import java.util.Map;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.logging.Level;
import java.util.logging.Logger;

import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
import java.util.Properties;

import fr.enseirb.webxml.data.xml.XMLMediator;
import fr.enseirb.webxml.util.XMLToolkit;

import fr.enseirb.webxml.util.ServletToolkit;
import fr.enseirb.webxml.util.StringFormatUtil;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;



/**
 * Servlet implementation class AboutServlet
 */
public class OwnershipServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = Logger.getLogger(XMLMediator.class.getName());

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public OwnershipServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		String URL = request.getRequestURI();
		String postData = ServletToolkit.getPostData(request);
		if (URL.endsWith("user/task/ownership/post")
			|| URL.endsWith("task/user/ownership/post")
		) {
			// <ownership taskId="1" userName="newOwner"/>
			Document doc = XMLToolkit.parseDocument(postData);
			Element ownElt = doc.getDocumentElement();

			String nom = ownElt.getAttribute("userName");
			String id = ownElt.getAttribute("taskId");

			String task = XMLMediator.getTask(Integer.parseInt(id));
			Document taskDoc = XMLToolkit.parseDocument(task);
			Element taskElt = taskDoc.getDocumentElement();

			// Modifier la valeur du fils « owner » de cette tâche en fonction du «
			// userName » indiqué dans le flux XML
			taskElt.getElementsByTagName("owner")
				.item(0).getFirstChild().setNodeValue(nom);

			XMLMediator.addOrModifyTask(taskElt);

			ServletToolkit.writeResponse(response,"Ok");
		} else if (URL.endsWith("isValid")) {
			boolean valid = XMLToolkit.isXMLValid(postData, "/resources/xsd/Ownership.xml");
			String res = XMLToolkit.createPostResult("Result of validating Ownership XML", valid);
			ServletToolkit.writeResponse(response, res);
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String URL = request.getRequestURI();
		Properties params = ServletToolkit.parseURLParams(request);
		String tasks = XMLMediator.getTasks();

		response.setHeader("Content-Type", "text/plain");

		if (URL.endsWith("user/ownership")) {
			if (params.containsKey("userName")) {
				// La liste des id des tâches pour un owner donné via une URL du type
				String name = params.getProperty("userName");
				String xpath = "//task[owner[text()='" + name + "']]/@id";
				List<String> ids = XMLToolkit.getXPathValues(tasks, xpath);
				String res = StringFormatUtil.sortAndFormat(ids);
				ServletToolkit.writeResponse(response, res);
			} else {
				ServletToolkit.writeResponse(response, "Error");
			}
		} else if (URL.endsWith("task/ownership")) {
			if (params.containsKey("taskId")) {
				// Le owner affecté à un id de tâche donnée via une URL du type
				String id = params.getProperty("taskId");
				String xpath = "//task[@id='" + id + "']/owner/text()";
				List<String> owner = XMLToolkit.getXPathValues(tasks, xpath);
				String res = StringFormatUtil.sortAndFormat(owner);
				ServletToolkit.writeResponse(response, res);
			} else {
				ServletToolkit.writeResponse(response, "Error");
			}
		} else if (URL.endsWith("csv")) {
			String xml = XMLMediator.getTasks();

			Map<String, String> xslParams = new HashMap<String, String>();
			String res  = XMLToolkit.transformXML(
				xml, "resources/xsl/common/task_list_csv.xsl", xslParams
			);
			ServletToolkit.writeResponse(response, res);
		}
	}
}
